package com.lanswon.qzsmk.service.systemManageService.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.lanswon.qzsmk.base.DwzPage;
import com.lanswon.qzsmk.dao.OrgMapper;
import com.lanswon.qzsmk.dao.RoleMapper;
import com.lanswon.qzsmk.dao.TellerMapper;
import com.lanswon.qzsmk.dao.UserMapper;
import com.lanswon.qzsmk.dao.UserOrgAdminMapper;
import com.lanswon.qzsmk.exception.ApplicationException;
import com.lanswon.qzsmk.exception.ErrorCode;
import com.lanswon.qzsmk.model.Org;
import com.lanswon.qzsmk.model.Role;
import com.lanswon.qzsmk.model.Teller;
import com.lanswon.qzsmk.model.User;
import com.lanswon.qzsmk.model.UserOrgAdmin;
import com.lanswon.qzsmk.service.systemManageService.TellerManageService;
import com.lanswon.qzsmk.util.CopyBean;
import com.lanswon.qzsmk.vo.SaveOrUpdateTellerVo;
import com.lanswon.qzsmk.vo.TellerAuthVo;
import com.lanswon.qzsmk.vo.TellerVo;
import com.lanswon.qzsmk.vo.UserVo;

@Service
public class TellerManageServiceImpl implements TellerManageService {

	@Autowired
	UserMapper um;

	@Autowired
	TellerMapper tm;
	
	@Autowired
	RoleMapper rm;
	
	@Autowired
	UserOrgAdminMapper  uoam;
	
	@Autowired
	OrgMapper om;

	@Override
	public void addTeller(SaveOrUpdateTellerVo t) throws ApplicationException {

		User u = um.queryFirstUser();

		if (u == null) {
			// 用户编号初始值
			t.setUserNo(100000);
		} else {
			if(um.queryUserByLoginName(t.getLoginName()) != null){
				throw new ApplicationException(ErrorCode.LOGIN_NAME_EXIST, "LoginName ["+t.getLoginName()+"] already exist!!!");
			}
			
			t.setUserNo(u.getUserNo() + 1);
		}
		String pwd = t.getLoginPassword();
        ByteSource credentialsSalt = ByteSource.Util.bytes(t.getLoginName());

	    Object result = new SimpleHash("MD5",pwd,credentialsSalt,1024);  
		
		
		t.setLoginPassword(result.toString());
		um.insert(t);
		t.setTellerId(t.getUserId());
		if(StringUtils.isEmpty(t.getBranchNo() )){
			t.setBranchNo(null);
		}
		tm.insert(t);
		if(StringUtils.isNotEmpty(t.getBranchNo()) ){
			
			UserOrgAdmin uoa = new UserOrgAdmin();
			uoa.setUserId(t.getUserId());
			
			Org o = om.queryOrgByNo(Integer.valueOf(t.getBranchNo()));
			uoa.setOrgId(o.getOrgId());
			uoam.insert(uoa);
		}
		
	}
	
	@Override
	public void modifyTeller_init(Integer tellId,String orgNo) {
		
		
		tm.updateBranchNo(tellId, orgNo);
	}

	@Override
	public void modifyTeller(SaveOrUpdateTellerVo t) {
		if(t.getLoginPassword()!=null){
			String pwd = t.getLoginPassword();
	        ByteSource credentialsSalt = ByteSource.Util.bytes(t.getLoginName());
		    Object result = new SimpleHash("MD5",pwd,credentialsSalt,1024);  
			t.setLoginPassword(result.toString());
		}
		um.update(t);
		User u = um.queryUserByNo(t.getUserNo());
		t.setTellerId(u.getUserId());
		tm.update(t);
		
		if(StringUtils.isNotEmpty(t.getBranchNo()) ){
			
			UserOrgAdmin uoa = new UserOrgAdmin();
			uoa.setUserId(u.getUserId());
			
			Org o = om.queryOrgByNo(Integer.valueOf(t.getBranchNo()));
			uoa.setOrgId(o.getOrgId());
			
			
			UserOrgAdmin uo = uoam.queryUserOrgAdminByUserId(u.getUserId());
			if(uo == null){
				uoam.insert(uoa);
			}else{
				uoam.update(uoa);
			}
			
		}else{
			uoam.deleteUserOrgAdminByUserId(u.getUserId());

		}
		
	}

	@Override
	public SaveOrUpdateTellerVo queryUserByUserNo(int userNo) throws Exception {
		if (userNo == 0) {
			throw new ApplicationException(ErrorCode.OBJECT_IS_NULL, "userNo is null");
		}

		SaveOrUpdateTellerVo vo = new SaveOrUpdateTellerVo();
		User u = um.queryUserByNo(userNo);
		Teller t = tm.queryTellerById(u.getUserId());
		vo = (SaveOrUpdateTellerVo) CopyBean.copyA2b(u, vo);
		vo = (SaveOrUpdateTellerVo) CopyBean.copyA2b(t, vo);
		return vo;
	}

	@Override
	public DwzPage<User> queryTellerByName(TellerVo t) {
		List<User> list = um.queryUserByNameOrNo(t);

		int totalCount = um.queryUserCountByNameOrNo(t);

		DwzPage<User> dp = new DwzPage<User>(t.getCurrentPage(), t.getNumPerPage(), totalCount);

		dp.setList(list);

		return dp;
	}

	@Override
	public void allocatTeller(Integer userNo, Integer BranchNo) throws Exception {
		if (userNo == null) {
			throw new ApplicationException(ErrorCode.OBJECT_IS_NULL, "userNo is null");
		}
		
		User u = um.queryUserByNo(userNo);
		
		if(BranchNo == null){
			uoam.deleteUserOrgAdminByUserId(u.getUserId());
		}else{
			
		
		
		
		UserOrgAdmin uoa = new UserOrgAdmin();
		uoa.setUserId(u.getUserId());
		
		Org o = om.queryOrgByNo(BranchNo);
		uoa.setOrgId(o.getOrgId());
		
		UserOrgAdmin uo = uoam.queryUserOrgAdminByUserId(u.getUserId());
		if(uo == null){
			uoam.insert(uoa);
		}else{
			uoam.update(uoa);
		}
		}
		tm.updateBranchNoByUserNo(userNo, BranchNo);
	}

	@Override
	public DwzPage<UserVo> showTellerByBranch(UserVo vo) {
		List<UserVo> list = tm.queryTellerByBranch(vo);

		int totalCount = tm.queryTellerCountByBranch(vo);
		DwzPage<UserVo> dp = new DwzPage<UserVo>(vo.getCurrentPage(), vo.getNumPerPage(), totalCount);
		dp.setList(list);
		return dp;
	}

	@Override
	public DwzPage<TellerAuthVo> queryTellerByUserNameOrUserNo(TellerAuthVo vo) {
		List<TellerAuthVo>  list = um.queryTellerByUserNameOrUserNo(vo);
		
		int totalCount = um.queryTellerCountByUserNameOrUserNo(vo);
		DwzPage<TellerAuthVo> dp = new DwzPage<>(vo.getCurrentPage(), vo.getNumPerPage(), totalCount);
		dp.setList(list);
				
		return dp;
	}

	@Override
	public Map<String, List<Role>> queryRoleByUser(Integer userId,Integer sysId) {
		List<Role> l = rm.queryRoleByUserId(userId, sysId);
		
		List<Role> ll = rm.queryAllRole();
		
		List<Role> lll = new ArrayList<>();
		boolean f =false;
		for(Role r:ll){
			for(Role rr:l){
				f = r.getRoleId().equals (rr.getRoleId());
				if(f ){
					break;
				}
			}
			if(!f){
				lll.add(r);
			}
		}
		Map<String, List<Role>> map = new HashMap<>();
		map.put("isSet", l);
		map.put("noSet", lll);
		return map;
	}

	@Override
	public void modifyTellerPassWord(SaveOrUpdateTellerVo t) {
		String pwd = t.getLoginPassword();
        ByteSource credentialsSalt = ByteSource.Util.bytes(t.getLoginName());

	    Object result = new SimpleHash("MD5",pwd,credentialsSalt,1024);  
		
		
		t.setLoginPassword(result.toString());
		um.update(t);
		
	}
}
